package com.zlj.province.city.linkage;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

@WebServlet("/CityServelt")
public class CityServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/xml;charset=utf-8");   //发送的是xml
		/*
		 * 获取省份的名称，加载该省对应的<province>元素！把元素转换为字符串发送给客户端
		 */
		/*
		 * 1、获取省份的名称
		 * 2、使用省份名称查找到对应的<province>元素
		 * 3、把<province>元素转换为字符串，发送！
		 */
		try {
			//得到Document
			SAXReader reader = new SAXReader();  
			InputStream io = this.getClass().getResourceAsStream("/china.xml");
			Document doc = reader.read(io);
			//获取参数
			String pname = request.getParameter("pname");   //获取省份的名称
			Element proEle = (Element)doc.selectSingleNode("//province[@name='" + pname + "']");
			String xmlStr = proEle.asXML();   //把元素转换为xml
			System.out.println(xmlStr);
			/*
			 * <province name="吉林">
			        <city>长春市</city>
			        <city>吉林市</city>
			        <city>四平市</city>
			        <city>辽源市</city>
			        <city>通化市</city>
			    </province>
			 */
			response.getWriter().print(xmlStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
